package com.greyshark.lib.bluetooth.utils

import android.content.Context
import android.media.MediaPlayer
import com.greyshark.lib.bluetooth.R

class MusicUtils {

  private val tag = MusicUtils::class.java.simpleName

  //播放无声音乐间隔
  var interval: Long = 5000L

  //无声音乐
  var enable: Boolean = false

  companion object {
    val instance: MusicUtils by lazy(mode = LazyThreadSafetyMode.SYNCHRONIZED) {
      MusicUtils()
    }
  }

  private var mediaPlayer: MediaPlayer? = null

  fun playMusic(context: Context) {
    try {
      if (enable){
        reset()
        mediaPlayer = MediaPlayer.create(context, R.raw.silence)
        mediaPlayer?.apply {
          setVolume(0f, 0f)
          setOnCompletionListener { mediaPlayer: MediaPlayer? ->
            ThreadPoolService.getInstance().post {
              Thread.sleep(interval)
              if (!isPlaying) {
                start()
              }
            }
          }
          setOnErrorListener { mp: MediaPlayer?, what: Int, extra: Int ->
            false
          }
          if (!isPlaying) {
            start()
          }
        }
      }
    } catch (e: Exception) {
      BleLogger.e(tag, "playMusic exception :$e")
    }
  }

  fun reset() {
    try {
      mediaPlayer?.apply {
        stop()
        release()
      }
      mediaPlayer = null
    } catch (e: Exception) {
      BleLogger.e(tag, "reset exception :$e")
    }
  }

}